<script setup lang="ts">

import {Delete, User, Watch} from "@element-plus/icons-vue";
import {onMounted, reactive, ref, watch} from "vue";
import {PatientArr, PatientResponseData} from "@/api/hospital/type.ts";
import {reqPatient} from "@/api/hospital";
import {reqAddOrUpdateUser, reqCertificatesType, reqCity, reqRemoveUser} from "@/api/user";
import {CascaderProps, ElMessage} from "element-plus";
import type {AddOrUpdateUser, CertificationArr, CertificationTypeResponseData} from "@/api/user/type.ts";
import {useRoute, useRouter} from "vue-router";
let patientArr = ref<PatientArr>();
let scene = ref<number>(0);
let certificationArr = ref<CertificationArr>([]);
let patientParams = reactive<AddOrUpdateUser>({
  id: 0,
  address:'',
  addressSelected: [],
  birthdate:'',
  certificatesNo:'',
  certificatesType:'',
  cityCode:'',
  contactsCertificatesNo:'',
  contactsCertificatesType:'',
  contactsName:'',
  contactsPhone:'',
  districtCode:'',
  isDeleted:0,
  isInsure:0,
  isMarry:0,
  name:'',
  phone:'',
  provinceCode:'',
  sex:0
})
let $route = useRoute();
let $router = useRouter();

onMounted(()=>{
  fetchPatient();
  getCertificationType();
  if($route.query.type=='add'){
    scene.value=1;
  }
  if($route.query.type=='edit'){
    scene.value=1;
  }
})
watch(()=>patientArr.value,()=>{
  let patient = patientArr.value?.find((item:any)=>{
    return item.id == $route.query.id
  })
  Object.assign(patientParams,patient)
})
const fetchPatient= async ()=>{
  let result:PatientResponseData = await reqPatient();
  if(result.code==200){
    patientArr.value=result.data;
  }
}
const addPatient =()=>{
  scene.value=1;
  reset();
}
const changeScene =(user:AddOrUpdateUser)=>{
  scene.value=1;
  Object.assign(patientParams,user);
}
// const removeUser =()=>{
//   // fetchPatient();
// }
const removeUser=async (id:number)=>{
  try{
    await reqRemoveUser(id);
    ElMessage({
      type:'success',
      message:'删除成功'
    })
    fetchPatient();
  }catch (error){
    ElMessage({
      type:'error',
      message:'删除失败'
    })
  }
}
const getCertificationType=async ()=>{
  let result :CertificationTypeResponseData = await reqCertificatesType();
  if(result.code==200){
    certificationArr.value = result.data;
  }
}
const props:CascaderProps ={
  lazy:true,
 async lazyLoad(node:any,resolve:any){
    let result:any = await reqCity(node.data.id||'86');
    let showData = result.data.map((item:any)=>{
      return{
        id:item.id,
        label:item.name,
        value:item.value,
        leaf:!item.hasChildren
      }

    })
    resolve(showData);
  }
}
const submit = async ()=>{
  try{
    //地址处理
      patientParams.provinceCode = patientParams.addressSelected[0] || ''
      patientParams.cityCode =patientParams.addressSelected[1] || ''
      patientParams.districtCode = patientParams.addressSelected[2] || ''
    let result:any = await reqAddOrUpdateUser(patientParams);
    if(result.code==200){
      ElMessage({
        type:'success',
        message:patientParams.id?'更新成功':'添加成功'
      })
    }else{
      ElMessage({
        type:'error',
        message:result.message
      })
    }
    if($route.query.type){
      $router.back();
    }else{
      scene.value=0;
    }
  }catch (error){
    ElMessage({
      type:'error',
      message:patientParams.id?'更新失败':'添加失败'
    })
  }

}
const reset = ()=>{
Object.assign(patientParams,{
  address:'',
  addressSelected: [],
  birthdate:'',
  certificatesNo:'',
  certificatesType:'',
  cityCode:'',
  contactsCertificatesNo:'',
  contactsCertificatesType:'',
  contactsName:'',
  contactsPhone:'',
  districtCode:'',
  isDeleted:0,
  isInsure:0,
  isMarry:0,
  name:'',
  phone:'',
  provinceCode:'',
  sex:0,
})
}
</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>就诊人管理</span>
        <el-button size="default" type="primary" :icon="User" @click="addPatient">添加就诊人</el-button>
      </div>
    </template>
    <div class="visiter" v-if="scene==0">
    <Visiter @changeScene="changeScene" v-for="(patient,index) in patientArr" :key="patient.id" class="item" :patient="patient" :index="index">
<!--             @removeUser="removeUser"-->
<!--    >-->
      <template  #otherBtn>
        <el-popconfirm @confirm="removeUser(patient.id)" :title="`你确定要删除${patient.name}吗？`" width="200px">
          <template #reference>
            <el-button type="danger" size="default" :icon="Delete"></el-button>
          </template>
        </el-popconfirm>

      </template>
    </Visiter>
    </div>
    <div class="form" v-if="scene==1">
      <el-divider content-position="left">就诊人信息</el-divider>
      <el-form style="width: 60%;margin: 10px auto">
        <el-form-item label="用户姓名" >
          <el-input placeholder="请你输入用户姓名" v-model="patientParams.name"></el-input>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-select style="width: 100%" placeholder="请选择证件类型" v-model="patientParams.certificatesType">
            <el-option label="身份证" v-for="item in certificationArr" :key="item.id" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input placeholder="请你输入证件号码"  v-model="patientParams.certificatesNo"></el-input>
        </el-form-item>
        <el-form-item label="用户性别">
         <el-radio-group v-model="patientParams.sex">
           <el-radio :label="1">男</el-radio>
           <el-radio :label="0">女</el-radio>
         </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker type="date" placeholder="请你选择日期" value-format="YYYY-MM-DD" v-model="patientParams.birthdate"/>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input placeholder="请你输入用户手机号码" v-model="patientParams.phone"></el-input>
        </el-form-item>
      </el-form>
      <el-divider content-position="left">建档信息（完善后部分医院首次就诊不排队建档）</el-divider>
      <el-form style="width: 60%;margin: 10px auto">
        <el-form-item label="婚姻状况">
          <el-radio-group v-model="patientParams.isMarry">
            <el-radio :label="1">已婚</el-radio>
            <el-radio :label="0">未婚</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="自费/医保">
          <el-radio-group v-model="patientParams.isInsure">
            <el-radio :label="1">自费</el-radio>
            <el-radio :label="0">医保</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="当前住址">
         <el-cascader :props="props"  v-model="patientParams.addressSelected"/>
        </el-form-item>
        <el-form-item label="详细地址：">
          <el-input v-model="patientParams.address" placeholder="应公安机关要求，请填写现真实住址"/>
        </el-form-item>
      </el-form>
      <el-divider content-position="left">联系人信息（选填）</el-divider>
      <el-form style="width: 60%;margin: 10px auto" label-width="80px">
        <el-form-item label="用户姓名">
          <el-input placeholder="请你输入用户姓名" v-model="patientParams.contactsName"></el-input>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-select style="width: 100%" placeholder="请选择证件类型" v-model="patientParams.contactsCertificatesType">
            <el-option label="身份证" v-for="item in certificationArr" :key="item.id" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input placeholder="请你输入证件号码" v-model="patientParams.contactsCertificatesNo"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input placeholder="请你输入用户手机号码"  v-model="patientParams.contactsPhone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="submit">提交</el-button>
          <el-button type="primary" size="default" @click="reset">重写</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<style scoped lang="scss">
.box-card{
  margin: 20px 0px;
  .card-header{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .visiter{
    display: flex;
    flex-wrap: wrap;
    .item{
      width: 32%;
      margin: 5px;
      border: solid 1px #ccc;
    }
  }
}
</style>
